package com.mars.common;

import com.mars.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 监听
 * @author MARS
 * @date 2017/12/28
 */

@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    /**
     * 处理前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request start. url:{}, params:{}",url, JsonMapper.obj2String(parameterMap));
        return true;
    }

    /**
     * 处理后调用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request finished. url:{}, params:{}",url, JsonMapper.obj2String(parameterMap));
        removeThreadLocalInfo();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request exeption. url:{}, params:{}",url, JsonMapper.obj2String(parameterMap));
        removeThreadLocalInfo();


    }

    /**
     * 进程结束时，要执行remove操作
     */
    public void removeThreadLocalInfo() {
        RequestHolder.remove();
    }
}
